package com.letv.business.flow.album;

import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import com.ledim.datastatistics.AnalysisDataUtils;
import com.ledim.datastatistics.LeDimAnalysisUtils;
import com.ledim.utils.LogUtil;
import com.ledim.utils.ToastUtil;
import com.letv.android.client.LetvSDK;
import com.letv.android.young.client.R;
import com.letv.business.flow.LeMPSession.PlayStateableHandler;
import com.letv.business.flow.PlayFlowEvents.FetchMetaEvent;
import com.letv.business.flow.PlayFlowEvents.PlayIdleEvent;
import com.letv.business.flow.album.AlbumPlayFlowObservable.FullControllerInitVideos;
import com.letv.business.flow.album.AlbumPlayFlowObservable.HandNotify;
import com.letv.business.flow.album.AlbumPlayFlowObservable.InitDownloadBtnNotify;
import com.letv.business.flow.album.AlbumPlayFlowObservable.PlayErrorCodeNotify;
import com.letv.business.flow.album.AlbumPlayFlowObservable.RequestCombineParams;
import com.letv.business.flow.album.AlbumPlayFlowObservable.SetSeekBarEndTimeNotify;
import com.letv.business.flow.album.AlbumPlayFlowObservable.VideoTitleNotify;
import com.letv.business.flow.album.listener.AlbumPlayFlowListener;
import com.letv.business.flow.album.listener.AlbumPlayingControllerListener;
import com.letv.business.flow.album.listener.LoadLayoutFragmentListener;
import com.letv.business.flow.album.listener.PlayAdFragmentListener;
import com.letv.business.flow.album.listener.PlayVideoFragmentListener;
import com.letv.business.flow.album.model.AlbumPlayInfo;
import com.letv.business.flow.play.PlayStatisticsUtils;
import com.letv.component.player.core.LetvMediaPlayerManager;
import com.letv.core.api.LetvRequest;
import com.letv.core.bean.AlbumNew;
import com.letv.core.bean.DataHull;
import com.letv.core.bean.FloatBallBeanList;
import com.letv.core.bean.IVideo;
import com.letv.core.bean.PlayRecord;
import com.letv.core.bean.ShackVideoInfoListBean.ShackVideoInfoBean;
import com.letv.core.bean.VideoBean;
import com.letv.core.config.LetvConfig;
import com.letv.core.constant.NetworkConstant;
import com.letv.core.constant.PlayConstant;
import com.letv.core.constant.PlayConstant.Authentication;
import com.letv.core.db.DBManager;
import com.letv.core.db.PreferencesManager;
import com.letv.core.network.volley.Volley;
import com.letv.core.network.volley.VolleyRequest;
import com.letv.core.network.volley.VolleyRequest.RequestManner;
import com.letv.core.network.volley.VolleyRequestQueue.RequestFilter;
import com.letv.core.network.volley.VolleyResponse.CacheResponseState;
import com.letv.core.network.volley.toolbox.SimpleResponse;
import com.letv.core.network.volley.toolbox.VolleyDbCache;
import com.letv.core.utils.BaseTypeUtils;
import com.letv.core.utils.LetvSDKUtils;
import com.letv.core.utils.LetvUtils;
import com.letv.core.utils.LogInfo;
import com.letv.core.utils.NetworkUtils;
import com.letv.core.utils.PlayUtils.PLAY_LEVEL;
import com.letv.core.utils.StatisticsUtils;
import com.letv.core.utils.TipUtils;
import com.letv.core.utils.UIsUtils;
import com.letv.datastatistics.DataStatistics;
import com.letv.datastatistics.util.DataConstant;
import com.letv.datastatistics.util.PageIdConstant;
import com.letv.tracker2.agnes.VideoPlay;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Observable;
import java.util.Observer;
import org.greenrobot.eventbus.EventBus;

//import com.letv.android.wo.ex.IWoFlowManager;
//import com.letv.android.wo.ex.WoInterface.LetvWoFlowListener;
//import com.letv.plugin.pluginconfig.commom.JarConstant;
//import com.letv.plugin.pluginloader.loader.JarLoader;

/**
 * 点播流程
 *
 * @author zhuqiao
 */
public class AlbumPlayFlow extends AlbumPlayBaseFlow
        implements AlbumPlayFlowListener, Observer
{

	public static final String ALBUM_FLOW_TAG = "albumFlowTag_";
	protected static final String REQUEST_CHECK_PLAY_RECORD = ALBUM_FLOW_TAG
	        + "checkPlayRecord";
	protected static final String REQUEST_DOWNLOAD = ALBUM_FLOW_TAG
	        + "download";
	public static final String REQUEST_VIDEO_PLAY_URL = ALBUM_FLOW_TAG
	        + "videoPlayUrl";
	protected static final String REQUEST_REAL_URL_BY_CDE = ALBUM_FLOW_TAG
	        + "requestRealurlByCde";
	protected static final String REQUEST_REAL_URL = ALBUM_FLOW_TAG
	        + "requestRealurl";
	protected static final String REQUEST_REAL_URL_FOR_WO = ALBUM_FLOW_TAG
	        + "requestRealurlForWo";
	protected static final String REQUEST_WIFI_REAL_URL = ALBUM_FLOW_TAG
	        + "requestWifiRealUrl";
	protected static final String REQUEST_VIDEO_CACHE = ALBUM_FLOW_TAG
	        + "requestVideoCache";

	// 请求数据失败后的重试次数，事不过三
	public static final int MAX_RETRY_TIMES = 2;

	/**
	 * 流程相关回调
	 **/
	protected AlbumPlayFlowObservable mObservable;
	/**
	 * videofragment接口
	 **/
	protected PlayVideoFragmentListener mVideoListener;
	/**
	 * loadlayout接口
	 **/
	protected LoadLayoutFragmentListener mLoadListener;
	/**
	 * 广告接口
	 **/
	protected PlayAdFragmentListener mAdListener;
	/**
	 * vip试看接口
	 **/
	// protected AlbumVipTrailListener mTrailListener;
	/**
	 * vip试看接口
	 **/
	protected AlbumPlayingControllerListener mAlbumPlayingListener;

	/**
	 * PlayStateableHandler
	 */
	public PlayStateableHandler playStateableHandler;

	protected FlowStyle mFlowStyle = FlowStyle.Album;

	private SharedPreferences mShared;
	// 从cde获取真实地址和从网络获取真实地址需要的时长，用于统计
	private long getRealUrlFromNetConsumetime, cdeConsumetime;

	protected enum FlowStyle
	{
		Album, Topic
	}

	private interface Callback
	{

		void callback();
	}

	public AlbumPlayFlow(Context context, int launchMode, Bundle bundle)
	{
		super(context, launchMode, bundle);

	}

	public void setObservable(AlbumPlayFlowObservable flowObservable)
	{
		mObservable = flowObservable;
	}

	public void setVideoListener(PlayVideoFragmentListener videoListener)
	{
		mVideoListener = videoListener;
	}

	public void setLoadListener(LoadLayoutFragmentListener loadListener)
	{
		mLoadListener = loadListener;
	}

	public void setAdListener(PlayAdFragmentListener adListener)
	{
		mAdListener = adListener;
	}

	// public void setAlbumVipTrailListener(AlbumVipTrailListener listener) {
	// mTrailListener = listener;
	// }

	public void setAlbumPlayingListener(AlbumPlayingControllerListener listener)
	{
		mAlbumPlayingListener = listener;
	}

	public AlbumPlayingControllerListener getAlbumPlayingListener()
	{
		return mAlbumPlayingListener;
	}

	public AlbumPlayFlowObservable getObserver()
	{
		return mObservable;
	}

	public LoadLayoutFragmentListener getLoadListener()
	{
		return mLoadListener;
	}

	public PlayVideoFragmentListener getVideoListener()
	{
		return mVideoListener;
	}

	public PlayAdFragmentListener getAdListener()
	{
		return mAdListener;
	}

	/**
	 * 启动
	 */
	@Override
	public void start()
	{

		if (mContext == null || mObservable == null || mVideoListener == null
		        || mLoadListener == null || mAdListener == null)
		{
			throw new NullPointerException("main flow param is null!");
		}

		mIsSkip = PreferencesManager.getInstance(mContext).isSkip();

		// mIsSkip = true;

		mPlayLevel = PreferencesManager.getInstance(mContext).getPlayLevel();
		mDownloadHd = PreferencesManager.getInstance(mContext).isDownloadHd();
		mPlayInfo.mReplayType = 1;
		// zhuqiao dlna
		mOldNetState = NetworkUtils.getNetworkType(mContext);
		mHardDecode = (LetvMediaPlayerManager.getInstance()
		        .getHardDecodeState() == 1);

		addPlayInfo("启动播放", "start");
		mIsLaunchPlay = true;
		addPlayInfo("aid:" + mAid + ",vid:" + mVid + ",cid:" + mCid + ",zid:"
		        + mZid + ",启动模式:" + getLaunchMode(), "");
		LogInfo.log("sguotao", "aid:" + mAid + ",vid:" + mVid + ",cid:" + mCid
		        + ",zid:" + mZid + ",启动模式:" + getLaunchMode());
		reportLanuchAndInit();
		startLoadingData();

	}

	protected void startLoadingData()
	{
		sRequestRealUrlConsumetime = System.currentTimeMillis();

		// statisticsLaunchAndInit(true);
		PlayStatisticsUtils.statisticsLaunchAndInit(mContext, this, true);
		mLoadListener.loading(true);

		if (mLaunchMode == PlayConstant.PLAY_ALBUM)
		{
			// 播放专辑
			// checkPlayRecord(true); SDK跳过播放记录
			requestVideo(false);
		}
		else if (mLaunchMode == PlayConstant.PLAY_VIDEO)
		{
			// 单视频
			// checkPlayRecord(false);
			requestVideo(false);
		}
		else if (mLaunchMode == PlayConstant.PLAY_DOWNLOAD)
		{
			// 缓存视频
			// requestDownload();
		}
		else
		{
			// 扫描本地视频
			// if (TextUtils.isEmpty(mAlbumUrl.realUrl)) {
			// return;
			// }
			// // 直接给播放地址的播放
			// File localVideo = new File(mAlbumUrl.realUrl);
			// if (localVideo.exists()) {
			// String fileName = localVideo.getName();
			// int index = fileName.indexOf(".");
			// String localVideoName = fileName.substring(0, index);
			// mObservable.notifyObservers(new
			// VideoTitleNotify(localVideoName));
			// } else {
			// int start = mAlbumUrl.realUrl.lastIndexOf("/");
			// int end = mAlbumUrl.realUrl.lastIndexOf(".");
			// if ((start != -1) && (end != -1) && (start < end)) {
			// mObservable.notifyObservers(new
			// VideoTitleNotify(mAlbumUrl.realUrl.substring(start + 1, end)));
			// }
			// }
			// mIsScanVideo = true;
			PlayStatisticsUtils.updatePlayDataStatistics(mContext, this,
			        DataConstant.StaticticsVersion2Constatnt.PlayerAction.PLAY_ACTION,
			        -1, false);
			IVideo mVideo = LetvSDK.getInstance().getmVideo();
			if (null == mVideo)
			{
				Log.e("LetvSDK", "the local file not exist!");
				return;
			}

			mVideoListener.initVideoView(false);
			mVideoListener.startPlayLocal(mVideo.getmFilePath(), 0);
			mObservable
			        .notifyObservers(new VideoTitleNotify(mVideo.getmTitle()));
			// mLocalPath = mAlbumUrl.realUrl;
			// mLocalSeek = mSeek;

			// zhuqiao dlna
			// if (dlna.isDlnaState) {
			// dlna.pushVideoToDlna(false);
			// } else {
			// mVideoListener.initVideoView(false);
			// mVideoListener.startPlayLocal(mAlbumUrl.realUrl, (int) mSeek *
			// 1000);
			// mLocalPath = mAlbumUrl.realUrl;
			// mLocalSeek = mSeek;
		}
	}

	/**
	 * 检查是否有播放记录
	 */
	// protected void checkPlayRecord(final boolean isAlbum) {
	// addPlayInfo("检查是否有播放记录", "");
	// sRequestRecodeConsumetime = System.currentTimeMillis();
	// new
	// LetvRequest<PlayRecord>(mContext).setRequestType(RequestManner.CACHE_ONLY)
	// .setTag(REQUEST_CHECK_PLAY_RECORD).setCache(new
	// VolleyDbCache<PlayRecord>() {
	//
	// @Override
	// public PlayRecord get(VolleyRequest<?> request) {
	// DownloadDBBean info =
	// DBManager.getInstance(mContext).getDownloadTrace(mContext).getTitleInFinish(mVid);
	// if (null != info) {
	// mDownloadDBBean = info;
	// mFilePath = info.getFilePath();
	// mIsDownloadFile = true;
	// mCurrDownloadFileIsHd = info.getIsHd() == 1 ? true : false;
	// mDownloadStreamLevel = info.getIsHd();
	// }
	//
	// // 如果播放记录已经生成，直接跳过
	// if (mPlayRecord != null) {
	// return mPlayRecord;
	// }
	//
	// if (isAlbum) {
	// if (mVid > 0) {
	// return LetvTools.copyBean(mVideoListener.getPoint(0, (int) mVid, false),
	// PlayRecord.class);
	// } else {
	// if (mCurPage == 1) {
	// return LetvTools.copyBean(mVideoListener.getPoint((int) mAid, 0, false),
	// PlayRecord.class);
	// }
	// }
	// } else {
	// return LetvTools.copyBean(mVideoListener.getPoint(0, (int) mVid, false),
	// PlayRecord.class);
	// }
	//
	// return null;
	// }
	//
	// @Override
	// public void add(VolleyRequest<?> request, PlayRecord response) {
	// }
	// }).setCallback(new SimpleResponse<PlayRecord>() {
	//
	// @Override
	// public void onCacheResponse(VolleyRequest<PlayRecord> request, PlayRecord
	// result, DataHull hull,
	// CacheResponseState state) {
	// + (System.currentTimeMillis() - sRequestRecodeConsumetime) +
	// "毫秒****************");
	// sRequestRecodeConsumetime = System.currentTimeMillis() -
	// sRequestRecodeConsumetime;
	// if (state == CacheResponseState.SUCCESS) {
	// addPlayInfo("请求播放记录成功", "");
	// }
	// onRequestPlayRecord(result);
	// }
	//
	// }).add();
	// }

	/**
	 * 请求完播放记录
	 *
	 * @param result
	 */
	protected void onRequestPlayRecord(PlayRecord result)
	{
		if (mIsDownloadFile && mDownloadDBBean != null)
		{
			mObservable.notifyObservers(
			        new VideoTitleNotify(mDownloadDBBean.getEpisodetitle()));
		}
		else if (result != null && !TextUtils.isEmpty(result.getTitle()))
		{
			mPlayRecord = result;
			int playRecordCid = mPlayRecord.getChannelId();

			// 如果是从别的端进入的都走播放记录

			boolean isFromMobile = (2 == mPlayRecord.getFrom().getInt());
			boolean notNeedPlayrecord = isFromMobile
			        && !"180001".equals(mPlayRecord.getvideoTypeKey());

			if ((playRecordCid == AlbumNew.Channel.TYPE_MOVIE
			        || playRecordCid == AlbumNew.Channel.TYPE_TV
			        || playRecordCid == AlbumNew.Channel.TYPE_CARTOON
			        || playRecordCid == AlbumNew.Channel.TYPE_DOCUMENT_FILM)
			        && notNeedPlayrecord)
			{
				mPlayRecord = null;
				// 这些频道的非正片不走播放记录
			}
			else
			{
				mObservable.notifyObservers(
				        new VideoTitleNotify(result.getTitle()));

				if (mPlayRecord.getTotalDuration() < 180)
				{
					// 3分钟之内的视频每次都从头开始播
					mPlayRecord.setPlayedDuration(0);
				}
				if (mFrom == PlayConstant.LAUNCH_FROM_SCANQRCODE)
				{
					mPlayRecord.setPlayedDuration(mIsSkip
					        && mPlayInfo.beginTime > 0 && mPlayInfo.hTime >= 0
					        && mPlayInfo.hTime < mPlayInfo.beginTime
					                ? mPlayInfo.beginTime : mPlayInfo.hTime);
					mPlayRecord.setFrom(1);
				}

				// !dlna.isDlnaState
				if (mPlayRecord.getTotalDuration() > 1800)
				{
					mLoadListener.loadingStart(LetvUtils.getPlayRecordType(
					        mContext, mPlayRecord, mPlayInfo.beginTime), null);
				}

				if (mSeek > 0)
				{
					mPlayRecord.setPlayedDuration(mSeek / 1000);
				}

				mVid = mPlayRecord.getVideoId();
				mPlayInfo.currTime = mPlayRecord.getPlayedDuration() * 1000;
				mPlayInfo.totalTime = mPlayRecord.getTotalDuration() * 1000;
			}
		}

		requestVideo(false);
		notifyTabRequestData();
	}

	/**
	 * 通知底部tab栏请求数据
	 */
	protected void notifyTabRequestData()
	{
		if (mFrom == PlayConstant.LAUNCH_FROM_NORMAL_VIDEO_RECOMMEND)
		{
			// 判断是否是从正片推荐跳转播放.如果是，那么设置vid为0(直接请求正片剧集信息，从第一集开始)
			mVid = 0;
		}
		mObservable.notifyObservers(new RequestCombineParams(mAid + "",
		        mVid + "", mCid + "", mZid + ""));
	}

	/**
	 * 请求视频详情和播放地址
	 */
	protected void requestVideo(boolean isNextPlayer)
	{
		mObservable.notifyObservers(AlbumPlayFlowObservable.ON_START_FETCHING);
		Volley.getQueue().cancelWithTag(REQUEST_VIDEO_PLAY_URL);

		// 播放器初始化
		mHasInited = false;
		mIsFirstPlay = true;

		// RequestVideoPlayUrl request = new RequestVideoPlayUrl();
		// request.setIsNextPlay(isNextPlayer);
		// request.requestNetwork();

		// 发送通知,开始状态机业务流程

		EventBus.getDefault().post(new FetchMetaEvent());

		LogInfo.log("sguotao", "发送eventBus,开始状态机业务流程:");

	}

	// /**
	// * 获取前贴广告
	// *
	// * @param isPause
	// * @return
	// */ protected boolean getFrontAdNormal(boolean isPause) {
	// addPlayInfo("开始请求前贴片广告", "");
	// if (mAlreadyPlayAd) {
	// return false;
	// }
	// sRequestAdsConsumetime = System.currentTimeMillis();
	// mAlreadyPlayAd = true;
	//
	// LogInfo.log("sguotao", "后台是否开启了广告：" +
	// AdsManager.getInstance().isShowAd());
	//
	// // 是否没有广告
	// boolean noAd = PreferencesManager.getInstance(mContext).isPipFlag() ||
	// (null != mCurrentPlayingVideo && mCurrentPlayingVideo.needPay()) ||
	// !mNeedPlayAd;
	//
	// if (PreferencesManager.getInstance(mContext).isPipFlag()) {// 从小窗播放回来
	// 跳过广告
	// PreferencesManager.getInstance(mContext).setPipFlag(false);
	// }
	//
	// if (!noAd) {// 有广告
	// if (mFirstRequest == 0) {
	// mFirstRequest = System.currentTimeMillis();
	// } else {
	// if ((System.currentTimeMillis() - mFirstRequest) < mRequestStep) {
	// mFirstRequest = System.currentTimeMillis();
	// return true;
	// }
	// }
	//
	// if (mCurrentPlayingVideo != null) {
	// mPlayInfo.mAdConsumeTime = System.currentTimeMillis();
	// if (isPause) {// 通知广告暂停
	// mAdListener.setADPause(true);
	// }
	// mAdListener.getDemandFrontAd(mCurrentPlayingVideo.getCid(), mAid, mVid,
	// mCurrentPlayingVideo
	// .getMid(), mPlayInfo.mUuidTimp, PreferencesManager.getInstance(mContext)
	// .getUserId(),
	// mCurrentPlayingVideo.getDuration() +
	// "", "", "0", LetvSDKUtils.getPinjie(), mCurrentPlayingVideo.needPay(),
	// false, false, mIsWo3GUser, PreferencesManager
	// .getInstance(mContext)
	// .getUtp());
	//
	// mVideoListener.setEnforcementWait(true);
	// }
	// LogInfo.log("sguotao", "请求广告");
	// return true;
	// }
	// // 无广告将isAdsFinish置为true，解决小窗跳半屏一直loading问题
	// mIsAdFinished = true;
	// mNeedPlayAd = true;
	// LogInfo.log("sguotao", "无广告");
	// return false;
	// }

	public long getPlayRecordStep()
	{
		if (mPlayRecord == null)
		{
			LogInfo.log("sguotao", "getPlayRecordStep=0");
			return 0;
		}

		if (mFrom == PlayConstant.LAUNCH_FROM_SCANQRCODE)
		{
			mPlayRecord.setPlayedDuration(
			        mIsSkip && mPlayInfo.beginTime > 0 && mPlayInfo.hTime >= 0
			                && mPlayInfo.hTime < mPlayInfo.beginTime
			                        ? mPlayInfo.beginTime : mPlayInfo.hTime);
		}
		else if (mIsSkip && mPlayInfo.beginTime > 0
		        && mPlayRecord.getPlayedDuration() <= mPlayInfo.beginTime)
		{
			// 当跳过片头片尾、片头时间大于0并且播放记录播放时间小于片头时间时，设置播放记录播放时间为片头时间
			mPlayRecord.setPlayedDuration(mPlayInfo.beginTime);
		}

		LogInfo.log("sguotao",
		        "getPlayRecordStep=" + mPlayRecord.getPlayedDuration());
		return mPlayRecord.getPlayedDuration();
	}

	/**
	 * 初始化半屏全屏播放控制器界面的下载按钮状态
	 */
	private void initDownloadButton()
	{
		// 专辑
		if (mVideoBelongedAlbum != null && mVideoBelongedAlbum.getType() == 1)
		{
			mHandler.post(new Runnable()
			{

				@Override
				public void run()
				{
					mObservable.notifyObservers(
					        new InitDownloadBtnNotify(mVideoBelongedAlbum));
				}
			});
		}
	}

	/**
	 * 从全屏播放时重新初始化一次
	 */
	// public void setCurrenStreamFromFullController() {
	// DownloadDBBean info = DownloadManager.getLocalVideoBean(mVid);
	// if (info == null) {
	// return;
	// }
	//
	// mDownloadStreamLevel = info.getIsHd();
	// setCurrentStreamFromDownload(mDownloadStreamLevel);
	// }
	private void setCurrentStreamFromDownload(int downloadStream)
	{
		switch (downloadStream)
		{
			case 1:
				mPlayLevel = PLAY_LEVEL.HIGH;
				break;
			case 2:
				mPlayLevel = PLAY_LEVEL.STANDARD;
				break;
			case 0:
				mPlayLevel = PLAY_LEVEL.LOW;
				break;
			default:
				break;
		}
	}

	/**
	 * 重新尝试播放
	 *
	 * @param needPlayAd
	 * @param isChangeStream
	 *            是否切换码流.true:直接切换播放地址播放；false:需要重现请求接口
	 */
	public void retryPlay(boolean needPlayAd, boolean isChangeStream)
	{
		sRequestRealUrlConsumetime = System.currentTimeMillis();

		mChangeStreamSeek = -1;
		mIsChangeStream = isChangeStream;

		mCdeStatusCode = -1;
		/**
		 * 从二维码扫描进入，播放下一集清除from
		 */
		if (mFrom == PlayConstant.LAUNCH_FROM_SCANQRCODE)
		{
			mFrom = PlayConstant.LAUNCH_FROM_CHANNEL;
		}

		mPlayInfo.mReplayType = 2;
		mObservable.notifyObservers(AlbumPlayFlowObservable.ON_HIDE_3G);
		mIsDownloadFile = false;
		mFilePath = null;
		mNeedPlayAd = needPlayAd;
		clearRequest();

		mVideoListener.pause();
		// mVideoListener.stopPlayback();
		if (isChangeStream)
		{
			PlayStatisticsUtils.updatePlayDataStatistics(mContext, this,
			        DataConstant.StaticticsVersion2Constatnt.PlayerAction.TG,
			        -1, false);

			mPlayInfo.mIpt = 2;
			mPlayInfo.mReplayType = 2;

		}
		// 打断+1
		mPlayInfo.mGlsbNum += 1;
		// statisticsLaunchAndInit(true);
		PlayStatisticsUtils.statisticsLaunchAndInit(mContext, this, true);

		mAdListener.pause();
		mAdListener.setPauseAd(false);
		if (!isChangeStream)
		{
			mAdListener.stopPlayback(needPlayAd);
		}

		createPlayRecord(true);

		if (isChangeStream)
		{
			mChangeStreamSeek = (int) mPlayInfo.currTime;
		}
		// 切换码流也重新请求合并接口，防止token失效
		requestVideo(false);
	}

	/**
	 * 清除请求
	 */
	private void clearRequest()
	{
		LogInfo.log("zhuqiao", "清除请求");
		Volley.getQueue().cancelAll(new RequestFilter()
		{

			@Override
			public boolean apply(VolleyRequest<?> request)
			{
				return request != null && !TextUtils.isEmpty(request.getTag())
				        && request.getTag().startsWith(ALBUM_FLOW_TAG);
			}
		});
	}

	/**
	 * 初始化播放记录，在没有播放记录的情况下
	 */
	public void createPlayRecord(boolean firstVideo)
	{
		if (mCurrentPlayingVideo == null)
		{
			return;
		}
		if (mPlayRecord != null)
		{
			if (mCurrentPlayingVideo != null)
			{
				mPlayRecord.setvideoTypeKey(
				        mCurrentPlayingVideo.getVideoTypeKey());
			}

			return;
		}

		mPlayRecord = new PlayRecord();

		mPlayRecord.setAlbumId((int) mAid);

		if (mCurrentPlayingVideo != null)
		{
			mPlayRecord.setVideoType(mCurrentPlayingVideo.getType());
			mPlayRecord.setImg300(mCurrentPlayingVideo.getPic300());
			mPlayRecord.setTitle(getTitle(mCurrentPlayingVideo));
			LogInfo.log("Emerson", "------final-----创建播放记录 videotypekey = "
			        + mCurrentPlayingVideo.getVideoTypeKey());
			mPlayRecord.setvideoTypeKey(mCurrentPlayingVideo.getVideoTypeKey());
			mPlayRecord.setChannelId(mCurrentPlayingVideo.getCid());
			mPlayRecord.setImg(mCurrentPlayingVideo.getPic());
			mPlayRecord.setCurEpsoid(
			        BaseTypeUtils.stof(mCurrentPlayingVideo.getEpisode()));
			mPlayRecord.setTotalDuration(mCurrentPlayingVideo.getDuration());
		}
		else if (mVideoBelongedAlbum != null)
		{
			mPlayRecord.setVideoType(mVideoBelongedAlbum.getType());
			mPlayRecord.setImg300(mVideoBelongedAlbum.getPic300());
		}
		mPlayRecord.setFrom(2);
		if (mSeek > 0)
		{
			mPlayRecord.setPlayedDuration(mSeek / 1000);
		}
		else
		{
			mPlayRecord.setPlayedDuration(0);
		}
		mPlayRecord.setVideoId((int) mVid);

		mPlayInfo.currTime = mPlayRecord.getPlayedDuration() * 1000;
		mPlayInfo.totalTime = mPlayRecord.getTotalDuration() * 1000;
		mPlayRecord.setUpdateTime(System.currentTimeMillis());
	}

	/**
	 * 设置标题
	 *
	 * @param video
	 */
	private String getTitle(VideoBean video)
	{
		if (video == null)
		{
			return "";
		}

		String channelName = LetvUtils.getChannelName(mContext, video.getCid());
		String name = "";
		if (TextUtils.equals(mContext.getString(R.string.channel_music),
		        channelName))
		{
			String singer = video.getSinger();
			name = video.getNameCn() + "  "
			        + BaseTypeUtils.ensureStringValidate(singer);
		}
		else
		{
			name = video.getNameCn();
		}

		return name;
	}

	public int getDownloadStreamLevel()
	{
		return mDownloadStreamLevel;
	}

	/**
	 * 同意处理，跳过片头，和提示跳过片头
	 */
	protected void startPlayLocal()
	{

		mIsScanVideo = false;
		mVideoListener.resetPlayFlag();
		mIsShowSkipEnd = true;
		mIsP2pMode = false;

		/*
		 * Added by chenhong, 添加本地视频播放记录的本地看过状态
		 */
		if (mDownloadDBBean != null)
		{
			DBManager.getInstance().getPlayTrace()
			        .insertPlayTraceByWatchedStatus(mDownloadDBBean.getAid(),
			                mDownloadDBBean.getVid());
		}

		/*
		 * 更新简介描述界面
		 */
		if (mDownloadDBBean != null)
		{
			VideoBean videoBean = new VideoBean();
			videoBean.setVid(mDownloadDBBean.getVid());
			videoBean.setPid(mDownloadDBBean.getAid());
			mAlbumPlayingListener.setPlayingVideoBean(videoBean);
		}

		getPlayRecordStep();

		if (mIsDownloadFile && !mIsInitReport)
		{
			mIsInitReport = true;
			if (!UIsUtils.isLandscape(mContext))
			{// 增加一个判断防止在全屏播放tip的时候上报半屏的曝光
				// 统计-半屏播放页的曝光--防止第一次进入的时候为0的情况
				LogInfo.LogStatistics("half play show");
				StringBuilder sb = new StringBuilder();
				sb.append(
				        DataConstant.StaticticsVersion2Constatnt.StaticticsName.STATICTICS_NAM_PAGE_ID)
				        .append(PageIdConstant.halpPlayPage);
				DataStatistics.getInstance().sendActionInfo(mContext, "0", "0",
				        LetvConfig.getPcode(mContext), "19", sb.toString(), "0",
				        mCurrentPlayingVideo.getCid() + "",
				        mCurrentPlayingVideo.getPid() + "", mVid + "",
				        LetvUtils.getUID(), null, null, null, null,
				        PreferencesManager.getInstance().isLogin() ? 0 : 1,
				        null);
			}
		}

		// 0，流畅； 1，高清； 2，标清；
		if (mDownloadDBBean != null)
		{
			mIsStartPlayLocalDownloadEnter = true;
			switch (mDownloadDBBean.getIsHd())
			{
				case 1:
					mPlayLevel = PLAY_LEVEL.HIGH;
					break;
				case 2:
					mPlayLevel = PLAY_LEVEL.STANDARD;
					break;
				case 0:
					mPlayLevel = PLAY_LEVEL.LOW;
					break;
				default:
					break;
			}

			// 5.8新加需求硬解播放器
			mStreamSupporter.resetHW();
			mStreamSupporter.hasSuperHd = false;

			if (mPlayLevel == PLAY_LEVEL.HIGH)
			{
				mCurrDownloadFileIsHd = true;
				mStreamSupporter.hasHd = true;
				mStreamSupporter.hasStandard = false;
			}
			else
			{
				mStreamSupporter.hasHd = false;
				mStreamSupporter.hasStandard = true;
			}
			mStreamSupporter.hasLow = false;
		}
		else
		{
			if (!mIsStartPlayLocalDownloadEnter)
			{
				mPlayLevel = PLAY_LEVEL.HIGH;
				mCurrDownloadFileIsHd = true;

				mStreamSupporter.hasHd = true;
				mStreamSupporter.hasStandard = false;
				mStreamSupporter.hasLow = false;
				mStreamSupporter.hasSuperHd = false;

				// 5.8新加需求硬解m3u8
				mStreamSupporter.resetHW();
			}
		}

		// 5.8新需求添加离线广告
		addOffAd();
		mDownloadDBBean = null;

		// wxf 20150204 判断，如果是预告片，则不显示小窗 v5.7之后要进行修改，让小窗也能播预告片
		mObservable
		        .notifyObservers(AlbumPlayFlowObservable.ON_CHECK_PIP_VISIBILE);
	}

	/**
	 * 天价离线广告
	 */
	protected void addOffAd()
	{
		addPlayInfo("本地播放器init上报 vid :", mVid + "");
		if (!PreferencesManager.getInstance().isPipFlag())
		{
			if (mDownloadDBBean != null && !mAlreadyPlayAd)
			{
				mPlayInfo.mAdConsumeTime = System.currentTimeMillis();
				mAdListener.getOfflineFrontAd(mDownloadDBBean.getCid(),
				        mDownloadDBBean.getAid(), mDownloadDBBean.getVid(),
				        mDownloadDBBean.getMmsid(), LetvUtils.getUUID(mContext),
				        PreferencesManager.getInstance().getUserId(),
				        mDownloadDBBean.getDuration() + "", "", "0", false,
				        false, false, true);
				mAlreadyPlayAd = true;
			}
			else
			{
				if (mIsAdFinished)
				{
					mVideoListener.initVideoView(true);
					mVideoListener.setEnforcementPause(false);
					mVideoListener.setEnforcementWait(false);
				}
				mVideoListener.startPlayLocal(mFilePath, mPlayRecord == null ? 0
				        : (int) mPlayRecord.getPlayedDuration() * 1000);
			}
		}
		else
		{
			if (!mHasAd)
			{
				PlayStatisticsUtils.updatePlayDataStatistics(mContext, this,
				        DataConstant.StaticticsVersion2Constatnt.PlayerAction.PLAY_ACTION,
				        -1, false);
			}

			PreferencesManager.getInstance().setPipFlag(false);
			mVideoListener.initVideoView(true);
			mVideoListener.setEnforcementPause(false);
			mVideoListener.setEnforcementWait(false);
			mVideoListener.startPlayLocal(mFilePath, mPlayRecord == null ? 0
			        : (int) mPlayRecord.getPlayedDuration() * 1000);
		}
	}

	/**
	 * 同意处理，跳过片头，和提示跳过片头
	 */
	public void startPlayNet()
	{
		mIsScanVideo = false;
		mVideoListener.resetPlayFlag();
		mIsAdFinished = true;

		if (TextUtils.isEmpty(mAlbumUrl.realUrl))
		{
			return;
		}

		if (mIsAdFinished)
		{
			mVideoListener.initVideoView(false);
			if (mAdListener.isPlaying()
			        && mVideoListener.getBufferPercentage() <= 0
			        && !mLoadListener.isLoadingShow())
			{
				mLoadListener.loading(false);
			}
		}
		else if (mCdeStatusCode != 200)
		{// 当广告缓冲完了开始cde预加载请求数据
			new Thread()
			{

				@Override
				public void run()
				{
					LogInfo.log("sguotao", "开始预加载:");
					try
					{
						URL url = new URL(mAlbumUrl.realUrl);
						HttpURLConnection conn = (HttpURLConnection) url
						        .openConnection();
						mCdeStatusCode = conn.getResponseCode();
						conn.getInputStream();
						if (mCdeStatusCode == 200)
						{
							LogInfo.log("sguotao", "开始预加载-------");
						}
					} catch (Exception e)
					{
						e.printStackTrace();
					}
				}

			}.start();
		}

		// String vf = BaseApplication.getInstance().getVideoFormat();
		String vf = LetvSDKUtils.getVideoFormat();
		if ("ios".equals(vf))
		{
			mPlayInfo.mVformat = "vformat=m3u8";
		}
		else
		{
			mPlayInfo.mVformat = "vformat=mp4";
		}
		if (mIsDownloadFile && !TextUtils.isEmpty(mFilePath))
		{
			return;
		}

		if (mPlayRecord != null)
		{
			getPlayRecordStep();
			mIsShowSkipEnd = true;
			mPlayInfo.mIsCload = true;
			if ((null != mCurrentPlayingVideo && mCurrentPlayingVideo.needPay())
			        || !mNeedPlayAd)
			{// 付费视频跳过广告
			}
			// zhuqiao dlna
			// if (dlna.isDlnaState) {
			// dlna.pushVideoToDlna(false);
			// } else {

			int playRecordProgress = (int) mPlayRecord.getPlayedDuration()
			        * 1000;
			// zhuqiao int position = dlna.dlnaProgress != -1 ?
			// dlna.dlnaProgress : playRecordProgress;
			int position = playRecordProgress;
			// zhuqiao dlna --

			/**
			 * 播放进度的设定
			 */
			IVideo mVideo = LetvSDK.getInstance().getmVideo();
			if (null != mVideo)
			{
				if (((int) mVideo.getmCurrentTime()
				        / 1000) > mPlayInfo.beginTime)
				{
					position = (int) mVideo.getmCurrentTime();
				}
				LogInfo.log("sguotao", "record position:" + position);
			}

			if (mChangeStreamSeek != -1)
			{
				LogInfo.log("sguotao",
				        "mChangeStreamSeek:" + mChangeStreamSeek);
				position = mChangeStreamSeek;
				mPlayRecord.setPlayedDuration(mChangeStreamSeek / 1000);
				mChangeStreamSeek = -1;
			}

			if (mIsAdFinished)
			{
				// 如果是普通3G，会有3G播放提示
				showToast3g();
				if (!mHasAd && !mIsChangeStream)
				{
					// updatePlayDataStatistics(DataConstant.StaticticsVersion2Constatnt.PlayerAction.PLAY_ACTION,
					// -1, false);
					PlayStatisticsUtils.updatePlayDataStatistics(mContext, this,
					        DataConstant.StaticticsVersion2Constatnt.PlayerAction.PLAY_ACTION,
					        -1, false);
				}

				mVideoListener.setEnforcementPause(false);
				mVideoListener.setEnforcementWait(false);
				final boolean isChangeStream = mIsChangeStream;
				LogInfo.log("sguotao",
				        "seek-----------------------" + position);
				if (mCurrentPlayingVideo != null)
				{
					mLoadListener
					        .loadingVideo(mCurrentPlayingVideo.getNameCn());
				}

				mVideoListener.startPlayNet(mAlbumUrl.realUrl, false, mIsDolby,
				        position, isChangeStream);
				mIsChangeStream = false;
				mIsStarted = true;
				// }
			}
		}
	}

	/**
	 * 是否需要显示 3G/2G/4G网络变化 弹出框
	 */
	private boolean shouldShowNetChangeDialog()
	{
		if (mIsWo3GUser)
		{
			return false;
		}

		if (!PreferencesManager.getInstance(mContext).isShow3gDialog())
		{
			return false;
		}

		LogInfo.log("zhuqiao", ".....showNetChangeDialog.....");
		boolean isDownLoad = mCurrentPlayingVideo == null ? false
		        : LetvUtils.isInFinish(mCurrentPlayingVideo.getId());
		if (!isDownLoad && !mIsDownloadFile
		        && ((NetworkUtils.getNetworkType(
		                mContext) == NetworkConstant.NETWORK_TYPE_2G
		                || NetworkUtils.getNetworkType(
		                        mContext) == NetworkConstant.NETWORK_TYPE_3G)))
		{// 非wifi播放非本地视频
			mLoadListener.finish();
			if (mHasAd)
			{
				mAdListener.setADPause(true);
			}
			mObservable.notifyObservers(AlbumPlayFlowObservable.ON_SHOW_3G);
			// 5.7 网络环境切换弹出框曝光
			mVideoListener.setEnforcementPause(true);
			mVideoListener.pause();
			// 统计
			StatisticsUtils.staticticsInfoPost(mContext, "19", "c68", "0015", 4,
			        null,
			        UIsUtils.isLandscape(mContext) ? PageIdConstant.fullPlayPage
			                : PageIdConstant.halpPlayPage,
			        null, null, null, null, null);
			return true;
		}
		return false;
	}

	/**
	 * 付费视频，试看开始
	 */
	// private void showVipTrailStart() {
	// if (null == mPayInfo) {
	// // 默认包月
	// mTrailListener.setStateForStartByHasLogined(true);
	// mCanToPip = false;
	// return;
	// }
	//
	// if (TextUtils.equals(mPayInfo.getIsForbidden(), "1")) {
	// // 封禁
	// mTrailListener.forbidden();
	// mCanToPip = false;
	// } else if (mPayInfo.getChargetype() == 0) {
	// // 单点
	// int ticketSize = mPayInfo.getTicketSize();
	// if (ticketSize == -1) {
	// // 服务器没有返回
	// if (PreferencesManager.getInstance().isLogin()) {
	// // 显示"开通会员"
	// mTrailListener.setStateForStartByHasLogined(true);
	// } else {
	// // 显示"开通会员"和"登录"
	// mTrailListener.setStateForStartByHasLogined(false);
	// }
	// } else if (ticketSize == 0) {
	// // 显示"去pc端买"
	// mTrailListener.setStateForStartByHasTicket(false);
	// } else {
	// // 显示"使用观影券"
	// mTrailListener.setStateForStartByHasTicket(true);
	// }
	// mCanToPip = false;
	// } else {
	// // 包月
	// if (PreferencesManager.getInstance(mContext).isLogin()) {
	// mTrailListener.setStateForStartByHasLogined(true);
	// } else {
	// mTrailListener.setStateForStartByHasLogined(false);
	// }
	// mCanToPip = false;
	// }
	// }
	public void setVideoBean(VideoBean video)
	{

		if (video == null)
		{
			return;
		}

		mCurrentPlayingVideo = video;
		if (mIsLaunchPlay)
		{
			mFirstVideo = video;
		}
		if (mPlayRecord != null)
		{
			mPlayRecord.setvideoTypeKey(video.getVideoTypeKey());
		}
		if (mAid <= 0 && video.getPid() > 0 && mIsLaunchPlay)
		{
			mAid = video.getPid();
		}

		/** 切换播放请求专辑详情更新简介显示 by king 2015-02-16 */
		if (mFirstVideo != null && mFirstVideo != video && video.getPid() > 0
		        && video.getPid() != mFirstVideo.getPid())
		{
			mAid = video.getPid();
		}

		initDownloadButton();
		mObservable.notifyObservers(new VideoTitleNotify(getTitle(video)));
		mPlayInfo.endTime = video.getEtime();
		mPlayInfo.beginTime = video.getBtime();
		if (mPlayRecord != null)
		{// !dlna.isDlnaState &&
			if (mFrom == PlayConstant.LAUNCH_FROM_SCANQRCODE)
			{
				mPlayRecord.setPlayedDuration(mIsSkip && mPlayInfo.beginTime > 0
				        && mPlayInfo.hTime >= 0
				        && mPlayInfo.hTime < mPlayInfo.beginTime
				                ? mPlayInfo.beginTime : mPlayInfo.hTime);
				mPlayRecord.setFrom(5);
			}
			if (video.getDuration() > 1800)
			{// !dlna.isDlnaState &&
				mLoadListener.loadingStart(LetvUtils.getPlayRecordType(mContext,
				        mPlayRecord, mPlayInfo.beginTime), video.getNameCn());
			}
		}

		if (video.getDuration() < 180)
		{
			if (mPlayRecord != null)
			{
				mPlayRecord.setPlayedDuration(0);
			}
		}

		// if (LetvUtils.isInFinish(video.getId())) {
		// mIsP2pMode = false;
		// mIsDownloadFile = true;
		// } else {
		mIsP2pMode = PreferencesManager.getInstance(mContext).getUtp();
		mIsDownloadFile = false;
		// }
		// if (!mIsDownloadFile) {
		// }

		mObservable.notifyObservers(new HandNotify(video));
		long endTime = video == null ? 0 : video.getEtime();
		mObservable.notifyObservers(
		        new SetSeekBarEndTimeNotify((int) endTime / 1000));
	}

	@Override
	public void setAlbum(AlbumNew album)
	{
		super.setAlbum(album);
		initDownloadButton();
	}

	/**
	 * 替换播放地址为免流量地址
	 */
	public void replaceUrlToFreeUrlForNetChange()
	{
		LogInfo.log("zhuqiao", "*****replaceUrlToFreeurlForNetChange*****");
		// UnicomWoFlowManager.getInstance().checkUnicomWoFreeFlow(mContext, new
		// LetvWoFlowListener() {
		// @SuppressWarnings("rawtypes")
		// @Override
		// public void onResponseOrderInfo(boolean isSupportProvince, boolean
		// isOrder, boolean isUnOrderSure,
		// String freeUrl, boolean isSmsSuccess) {
		// if (mContext == null) { // 联通异步initsdk，回调mContext可能为空
		// return;
		// }
		//
		// mIsWo3GUser = isOrder;
		// mIsPlayFreeUrl = false;
		// Class clazz_wfm = JarLoader.loadClass(mContext,
		// JarConstant.LETV_WO_NAME,
		// JarConstant.LETV_WO_PACKAGENAME, "WoFlowManager");
		// IWoFlowManager woFlowManager = (IWoFlowManager)
		// JarLoader.invokeStaticMethod(clazz_wfm, "getInstance",
		// null, null);
		// boolean isNetWo = NetworkUtils.getNetTypeForWo();
		// boolean isPhoneNumNull =
		// TextUtils.isEmpty(woFlowManager.getPhoneNum(mContext));
		// if (isSupportProvince && !mIsWo3GUser && mIsSdkInitFail &&
		// !isPhoneNumNull && isNetWo) {
		// mIsSdkInitFail = false;
		// if (UnicomWoFlowManager.DISABLE_WO) {
		// if (mVideoListener.isPlaying() && !mAdListener.isPlaying()) {
		// mHandler.post(new Runnable() {
		//
		// @Override
		// public void run() {
		// shouldShowNetChangeDialog();
		// }
		// });
		// }
		// } else {
		// UnicomWoFlowDialogUtils.woMainDialog(mContext, new
		// UnicomDialogClickListener() {
		//
		// @Override
		// public void onConfirm() {
		// }
		//
		// @Override
		// public void onCancel() {
		// if (mVideoListener.isPlaying() && !mAdListener.isPlaying()) {
		// mHandler.post(new Runnable() {
		//
		// @Override
		// public void run() {
		// shouldShowNetChangeDialog();
		// }
		// });
		// }
		// }
		//
		// @Override
		// public void onResponse(boolean isShow) {
		// }
		// }, "AlbumPlayActivity");// zhuqiao 名称
		// }
		// }
		//
		// if (!isOrder && isPhoneNumNull && isNetWo) {
		// if (UnicomWoFlowManager.DISABLE_WO) {
		// if (mVideoListener.isPlaying() && !mAdListener.isPlaying()) {
		// mHandler.post(new Runnable() {
		//
		// @Override
		// public void run() {
		// shouldShowNetChangeDialog();
		// }
		// });
		// }
		// } else {
		// UnicomWoFlowDialogUtils.woInikSdkFailDialog(mContext, new
		// UnicomDialogClickListener() {
		//
		// @Override
		// public void onConfirm() {
		// mIsSdkInitFail = true;
		// replaceUrlToFreeUrlForNetChange();
		// }
		//
		// @Override
		// public void onCancel() {
		// if (mVideoListener.isPlaying() && !mAdListener.isPlaying()) {
		// mHandler.post(new Runnable() {
		//
		// @Override
		// public void run() {
		// shouldShowNetChangeDialog();
		// }
		// });
		// }
		// }
		//
		// @Override
		// public void onResponse(boolean isShow) {
		// }
		// });
		// }
		// } else if (isOrder) {
		// requestWifiRealUrl();
		// } else if (!isOrder) {
		// mHandler.post(new Runnable() {
		//
		// @Override
		// public void run() {
		// if (!shouldShowNetChangeDialog()) {
		// startPlayWith3g();
		// }
		// }
		// });
		// }
		// }
		// });
	}

	/**
	 * 网络切换
	 */
	protected void onNetChange()
	{
		int currentState = NetworkUtils.getNetworkType(mContext);
		if (mOldNetState == currentState)
		{
			return;
		}

		switch (currentState)
		{
			case NetworkConstant.NETWORK_TYPE_2G:
			case NetworkConstant.NETWORK_TYPE_3G:
				onNetChangeTo2GOr3G();
				break;
			case NetworkConstant.NETWORK_TYPE_WIFI:
				onNetChangeToWifi();
				break;
			case NetworkConstant.NETWORK_TYPE_NO_NET:
				onNetChangeToNoNet();
				break;
		}

		mOldNetState = currentState;
		// 统计网络切换 ccx
		VideoPlay videoPlay = getCommonVideoPlay();
		videoPlay
		        .switchNetworkModel(AnalysisDataUtils.getNetworkType(mContext));
		LeDimAnalysisUtils.reportPlayEvent(videoPlay);
	}

	/**
	 * 网络切换至2g或者3g
	 */
	protected void onNetChangeTo2GOr3G()
	{
		if (mLaunchMode == PlayConstant.PLAY_DEFAULT)
		{// 播放本地视频时，切3g仅仅提示toast
			ToastUtil.toast(TipUtils.getTipMessage(mContext, "100006",
			        R.string.play_net_2g3g4g_tag));
			return;
		}

		if (mCurrentPlayingVideo != null)
		{
			// 正在播放正片
			boolean isDownLoad = LetvUtils
			        .isInFinish(mCurrentPlayingVideo.getId());
			if (!isDownLoad && TextUtils.isEmpty(mFilePath) && !mIsDownloadFile
			        && mLaunchMode != PlayConstant.PLAY_DOWNLOAD)
			{
				if (!TextUtils.isEmpty(mAlbumUrl.ddUrl))
				{
					replaceUrlToFreeUrlForNetChange();
				}
				else
				{
					requestVideo(false);
				}
			}
			else
			{
				ToastUtil.toast(TipUtils.getTipMessage(mContext, "100006",
				        R.string.play_net_2g3g4g_tag));
			}
		}
		else
		{
			startLoadingData();
		}
	}

	/**
	 * 网络切换至wifi
	 */
	private void onNetChangeToWifi()
	{
		if (mHasAd)
		{
			mAdListener.onResume();
		}

		mVideoListener.setEnforcementPause(false);
		ToastUtil.toast(TipUtils.getTipMessage(mContext, "100007",
		        R.string.play_net_iswifi_tag));
		mObservable.notifyObservers(AlbumPlayFlowObservable.ON_HIDE_3G);
		// if (mIsPlayFreeUrl) {
		// // 正在使用免流量播放地址
		// mIsPlayFreeUrl = false;
		// mIsWo3GUser = false;
		// mVideoListener.setIsSeekTo0(false);
		// mVideoListener.pause();
		// requestWifiRealUrl();
		// } else {
		if (!TextUtils.isEmpty(mAlbumUrl.ddUrl))
		{
			if (mVideoListener.isEnforcementPause() && !mAdListener.isPlaying())
			{
				mLoadListener.loadingVideo(mCurrentPlayingVideo == null ? null
				        : mCurrentPlayingVideo.getNameCn());
				mVideoListener.setEnforcementPause(false);
			}
			if (mLaunchMode != PlayConstant.PLAY_DEFAULT
			        && mVideoListener.isSeekTo0())
			{// 小窗回来时，会seek到指定pos，这个又给seek到0了。所以添加这种判断
				if (mPlayCallBackState == 7)
				{
					requestVideo(false);
				}
				else if (TextUtils.isEmpty(mAlbumUrl.ddUrl))
				{
					requestVideo(false);
				}
				else
				{
					if (mIsStarted)
					{
						mVideoListener
						        .seekTo(mVideoListener.getCurrentPosition());
						mVideoListener.start();
					}
					else
					{ // 3G进入播放，再连wifi没初始化VideoView
						requestVideo(false);
					}
				}
			}
		}
		else
		{
			if (mOldNetState != -1)
			{
				if (!mVideoListener.isPlaying() && mIsFirstPlay)
				{
					startLoadingData();
				}
			}
		}
		// }
	}

	/**
	 * 切换到无网状态
	 */
	private void onNetChangeToNoNet()
	{
		// zhuqiao dlns
		// if (mTsController != null && mTsController.loadingDialog != null) {
		// mTsController.loadingDialog.dismiss();
		// }

		if (!TextUtils.isEmpty(mAlbumUrl.realUrl) && !isLocalFile())
		{
			boolean isBufferPlayOver = mVideoListener
			        .getCurrentPosition() >= mVideoListener
			                .getBufferPercentage();
			if (isBufferPlayOver && mVideoListener.isPaused())
			{
				String tip = TipUtils.getTipMessage(mContext, "100075",
				        R.string.network_cannot_use_try_later);
				mLoadListener.requestError(tip, "");
				// mTrailListener.hide();
				mObservable.notifyObservers(new PlayErrorCodeNotify("", true));
			}
		}
	}

	// --------------------- 对外接口实现 ---------------------

	@Override
	public void getFrontAd()
	{
		if (mAlreadyPlayAd)
		{
			return;
		}

		if (mCurrentPlayingVideo != null)
		{
			mAdListener.getDemandFrontAd(mCurrentPlayingVideo.getCid(), mAid,
			        mVid, mCurrentPlayingVideo.getMid(), mPlayInfo.mUuidTimp,
			        PreferencesManager.getInstance().getUserId(),
			        mCurrentPlayingVideo.getDuration() + "", "", "0",
			        LetvSDK.getPinjie(), mCurrentPlayingVideo.needPay(), true,
			        false, mIsWo3GUser,
			        PreferencesManager.getInstance().getUtp());

			mVideoListener.setEnforcementWait(true);
		}
	}

	@Override
	public void setAdCount(int adCount)
	{
		super.setAdCount(adCount);
		mPlayInfo.mAdCount = adCount;
	}

	/**
	 * 开始播放广告
	 */
	public void startPlayAd(long time)
	{
		LogUtil.e("startPlayAd time===" + time);
		if (mPlayInfo.mIsStaticsEnd)
		{
			PlayStatisticsUtils.updatePlayDataStatistics(mContext, this,
			        DataConstant.StaticticsVersion2Constatnt.PlayerAction.PLAY_ACTION,
			        -1, false);
		}
		if (mPlayInfo.mAdsPlayFirstFrameTime == 0 && !mPlayInfo.mIsPlayingAds)
		{
			mPlayInfo.mAdsPlayFirstFrameTime = time;
		}
		LogInfo.log("jc666",
		        "ads start play:" + mPlayInfo.mAdsPlayFirstFrameTime);
	}

	@Override
	public void onBackgroundStart()
	{
		addPlayInfo("广告缓冲完成，开始进行正片预加载", "");
		mIsAdFinished = false;
		if (!mIsDownloadFile && mDownloadDBBean == null)
		{
			if (TextUtils.isEmpty(mAlbumUrl.realUrl))
			{
				LogInfo.log("ads", "realUrl is null");
			}
			else
			{
				LogInfo.log("zhuqiao", "---getMainClientBackGroundStart---");
				startPlayNet();
				LogInfo.log("ads", "realUrl is " + mAlbumUrl.realUrl);
			}
		}
	}

	@Override
	public void onAdsFinish(boolean byHand)
	{
		addPlayInfo("广告播放完毕", "");
		LogUtil.e("广告播放完毕");
		mIsAdFinished = true;
		if (mHasAd && !mIsDolby)
		{
			mLoadListener.finish();
		}
		mHasAd = false;
		mAdCount = 0;
		if (mCurrentPlayingVideo != null)
		{
			mAdListener.setPauseAd(false);
			mIVideoStatusInformer = mAdListener.getIVideoStatusInformer();
		}
		mVideoListener.setEnforcementWait(false);

		mPlayInfo.mAdConsumeTime = System.currentTimeMillis()
		        - mPlayInfo.mAdConsumeTime;

		if (!byHand)
		{
			if (mIsDownloadFile && !TextUtils.isEmpty(mFilePath))
			{
				// zhuqiao dlna
				startPlayLocal();
			}
			else
			{
				LogInfo.log("zhuqiao", "------------onAdsFinish------------");
				if (mPlayCallBackState == 7)
				{// 某些设备上，播放完广告后，无法播放视频
					if (TextUtils.isEmpty(mAlbumUrl.realUrl))
					{
						requestVideo(false);
					}
					else
					{
						if (!shouldShowNetChangeDialog())
						{
							startPlayNet();
						}
					}
				}
				else
				{
					if (mPlayRecord != null)
					{
						if (!shouldShowNetChangeDialog())
						{
							LogUtil.e("mPlayRecord != null startPlayNet");
							startPlayNet();
						}
					}
					else
					{
						startPlayNet();
					}
				}
			}
		}
	}

	@Override
	public void onClickShipAd()
	{
		mIsClickShipAd = true;
	}

	/**
	 * 从进入到播放整个流程，区分失败的原因进行重试 记录到播放流程，哪一个环节失败了；0 无失败 ， 1,
	 * 专辑详情，2，视频详情，3，视频列表，4，canplay和付费信息接口，5，videofile接口，6，调度中，7，缓冲中或播放中
	 */
	@Override
	public void requestErr()
	{
		mLoadListener.loading(false);
		mObservable.notifyObservers(new PlayErrorCodeNotify("", false));
		EventBus.getDefault().post(new PlayIdleEvent());

		switch (mPlayCallBackState)
		{
			case 1:
				if (mLaunchMode == PlayConstant.PLAY_DOWNLOAD)
				{
					// 播放本地视频，刷新重试不走checkDownloadTaskPlayerLibs
					requestVideo(false);
				}
				else
				{
					LogUtil.e("123445555555 requestErr start");
					start();
				}
				// zhuqiao 统计
				PlayStatisticsUtils.staticticsErrorInfo(mContext, this,
				        DataConstant.ERRORCODE.REQUEST_ALBUM_DETAIL_ERROR,
				        "playerError", 0, -1);
				break;
			case 2:
				requestVideo(false);
				// 统计
				PlayStatisticsUtils.staticticsErrorInfo(mContext, this,
				        DataConstant.ERRORCODE.REQUEST_VIDEO_DETAIL_ERROR,
				        "playerError", 0, -1);
				break;
			case 3:
				requestVideo(false);
				// 统计
				PlayStatisticsUtils.staticticsErrorInfo(mContext, this,
				        DataConstant.ERRORCODE.REQUEST_VIDEO_LIST_ERROR,
				        "playerError", 0, -1);
				break;
			case 4:
			case 5:
				LogInfo.log("zhuqiao",
				        "---onRequestErr RequestVideoFile 55---");
				requestVideo(false);
				// 统计
				PlayStatisticsUtils.staticticsErrorInfo(mContext, this,
				        DataConstant.ERRORCODE.REQUEST_VIDEO_FILE_ERROR,
				        "playerError", 0, -1);
				break;
			case 6:
				LogInfo.log("zhuqiao", "---onFinish RequestVideoFile 66---");
				requestVideo(false);
				// 统计
				PlayStatisticsUtils.staticticsErrorInfo(mContext, this,
				        DataConstant.ERRORCODE.REQUEST_DDURLS_ERROR,
				        "playerError", 0, -1);
				break;
			case 7:
				if (TextUtils.isEmpty(mAlbumUrl.realUrl))
				{
					LogInfo.log("zhuqiao",
					        "---onRequestErr 77 RequestVideoFile---");
					requestVideo(false);
				}
				else
				{
					if (mAid <= 0 && mVid <= 0)
					{
						mVideoListener.startPlayLocal(mAlbumUrl.realUrl, 0);
					}
					else
					{
						LogInfo.log("zhuqiao",
						        "---onRequestErr 77 else RequestVideoFile---");
						requestVideo(false);
					}
				}
				// 统计
				PlayStatisticsUtils.staticticsErrorInfo(mContext, this,
				        DataConstant.ERRORCODE.REQUEST_LOADING_ERROR,
				        "playerError", 0, -1);
				break;
			case 8:
				// 使用观影券时断网的刷新重试
				break;
			default:
				LogInfo.log("zhuqiao", "---onRequestErr default---");
				if (mLaunchMode == PlayConstant.PLAY_DOWNLOAD)
				{
					// 播放本地视频，刷新重试不走checkDownloadTaskPlayerLibs
					requestVideo(false);
				}
				else
				{
					LogInfo.log("zhuqiao", "---onRequestErr  else---");
					mPlayCallBackState = 2;
					if (!mIsDownloadFile
					        && !NetworkUtils.isNetworkAvailable(mContext)
					        && mLoadListener.isLoadingShow())
					{
					}
					else
					{
						LogUtil.e("123445555555 requestErr defalut start");
						start();
					}
				}
				break;
		}
	}

	@Override
	public void play(VideoBean video)
	{
		if (video == null)
		{
			return;
		}

		if (mCurrentPlayingVideo != null)
		{
			setVideoBean(video);

			if (!mCurrentPlayingVideo.canPlay()
			        && mCurrentPlayingVideo.needJump()
			        && TextUtils.equals(mCurrentPlayingVideo.getJumptype(),
			                Authentication.WEB_JUMP))
			{
				if (!TextUtils.isEmpty(video.getJumpLink()))
				{
					// 同一剧集下的视频，如果第一个需要外跳，那么其他视频自动外跳
					mLoadListener.autoJumpWeb(video);
				}
			}
		}

		play(video.getVid(), true);
	}

	@Override
	public void playNext(long vId)
	{
		mCurrentPlayingVideo = null;
		play(vId, true);
	}

	@Override
	public void playNext(VideoBean video)
	{
		play(video);
	}

	/**
	 * 切换同一专辑下的其它视频播放
	 *
	 * @param vId
	 * @param isPlayAlbumOther
	 *            标记是否播放下一集
	 */
	private void play(long vId, boolean isPlayAlbumOther)
	{
		mChangeStreamSeek = -1;
		if (vId == mVid && mLoadListener.getErrState() == 0)
		{
			// 无更新
			return;
		}
		sRequestRealUrlConsumetime = System.currentTimeMillis();

		mAlreadyPlayAd = false;
		mCdeStatusCode = -1;
		mIsLaunchPlay = false;

		/**
		 * 从二维码扫描进入，播放下一集清除from
		 */
		if (mFrom == PlayConstant.LAUNCH_FROM_SCANQRCODE)
		{
			mFrom = PlayConstant.LAUNCH_FROM_CHANNEL;
		}

		format();

		StatisticsUtils.setPageId(UIsUtils.isLandscape(mContext)
		        ? PageIdConstant.fullPlayPage : PageIdConstant.halpPlayPage);
		if (isPlayAlbumOther)
		{
			mFrom = PlayConstant.LAUNCH_FROM_PLAY_PAGE;
			StatisticsUtils.setActionProperty("-", -1,
			        UIsUtils.isLandscape(mContext) ? PageIdConstant.fullPlayPage
			                : PageIdConstant.halpPlayPage);
		}

		mVid = vId;
		mIsDownloadFile = false;
		mIsStarted = false;
		mAlbumUrl.ddUrl = null;
		mPlayRecord = null;
		mFilePath = null;
		mNeedPlayAd = true;

		resetTime();
		createPlayRecord(false);
		// 统计播放-launch-init
		// statisticsLaunchAndInit(true);
		PlayStatisticsUtils.statisticsLaunchAndInit(mContext, this, true);
		LogInfo.LogStatistics("albumplayflow 切换同一专辑下的其它视频播放-launch-init");

		requestVideo(isPlayAlbumOther);

	}

	public void format()
	{
		clearRequest();

		mVideoListener.pause();
		mVideoListener.stopPlayback();
		mVideoListener.setEnforcementWait(false);
		mVideoListener.setEnforcementPause(false);
		mVideoListener.hideRecommendTip();

		mAdListener.cancelRequestFrontAdTask();
		if (mAdListener.getIVideoStatusInformer() != null)
		{
			mAdListener.getIVideoStatusInformer().destory();
			mAdListener.setIVideoStatusInformer(null);
		}
		mAdListener.setPauseAd(false);
		mAdListener.pause();
		mAdListener.stopPlayback(false);
		mIVideoStatusInformer = null;

		mLoadListener.finish();
		mObservable
		        .notifyObservers(AlbumPlayFlowObservable.ON_CONTROLLER_DISABLE);
		mObservable.notifyObservers(AlbumPlayFlowObservable.ON_HIDE_3G);

		EventBus.getDefault().post(new PlayIdleEvent());

	}

	@Override
	public void startPlayWith3g()
	{
		PreferencesManager.getInstance().setShow3gDialog(false);
		LogInfo.log("zhuqiao", "---onChange---star3g");
		mVideoListener.setEnforcementPause(false);
		if (mHasAd)
		{
			mAdListener.onResume();
		}
		mObservable.notifyObservers(AlbumPlayFlowObservable.ON_HIDE_3G);
		if (mIsStarted)
		{
			showToast3g();
			mVideoListener.startOverall();
		}
		else
		{
			mLoadListener.loading(true);
			requestVideo(false);
		}
	}

	private void showToast3g()
	{
		if (mIsWo3GUser)
		{
			return;
		}

		if (NetworkUtils.isNetworkAvailable(mContext) && (NetworkUtils
		        .getNetworkType(mContext) == NetworkConstant.NETWORK_TYPE_2G
		        || NetworkUtils.getNetworkType(
		                mContext) == NetworkConstant.NETWORK_TYPE_3G))
		{
			ToastUtil.toast(TipUtils.getTipMessage(mContext, "100006",
			        R.string.play_net_2g3g4g_tag));
		}
	}

	protected void handlerFloatBall()
	{
		if (mCurrentPlayingVideo != null)
		{
			mVideoListener.handlerFloatBall(
			        FloatBallBeanList.FLOAT_CHANNEL_CATETROY_SEVEN,
			        mCurrentPlayingVideo.getCid());
		}
	}

	public ShackVideoInfoBean getShackVideoInfo()
	{
		if (mAid > 0 && mVid > 0)
		{
			ShackVideoInfoBean info = new ShackVideoInfoBean();
			info.setAid(mAid);
			info.setVid(mVid);
			info.setPlaytime(
			        (mPlayInfo.currTime > 0 ? mPlayInfo.currTime : 0) / 1000);

			return info;
		}

		return null;
	}

	// --------------------- 播放流程观察者监听 ---------------------

	@Override
	public void update(Observable observable, Object data)
	{
		if (data instanceof String)
		{
			String notify = (String) data;
			if (TextUtils.equals(PlayObservable.ON_NET_CHANGE, notify))
			{
				onNetChange();
			}
			else if (TextUtils.equals(PlayObservable.ON_CALL_STATE_IDLE,
			        notify))
			{
				// statisticsLaunchAndInit(true);
				PlayStatisticsUtils.statisticsLaunchAndInit(mContext, this,
				        true);
			}
		}
	}

	/**
	 * 请求视频信息
	 *
	 * @author zhuqiao
	 */
	public class RequestVideoPlayUrl
	{

		private boolean mIsNextPlayer;

		protected boolean mIsLocalSuccess = false;

		public RequestVideoPlayUrl()
		{
		}

		public void setIsNextPlay(boolean isNextPlayer)
		{
			mIsNextPlayer = isNextPlayer;
		}

		/**
		 * 请求缓存数据
		 */
		public void startRequestCache()
		{
			addPlayInfo("检查视频是否已缓存", "");
			sRequestLocalConsumetime = System.currentTimeMillis();
			new LetvRequest<VideoBean>(mContext)
			        .setRequestType(RequestManner.CACHE_ONLY)
			        .setTag(REQUEST_VIDEO_CACHE)
			        .setCache(new VolleyDbCache<VideoBean>()
			        {

				        @Override
				        public VideoBean get(VolleyRequest<?> request)
				        {
					        // requestCache();
					        return mIsDownloadFile ? new VideoBean() : null;
				        }

				        @Override
				        public void add(VolleyRequest<?> request,
				                VideoBean response)
				        {
				        }
			        }).setCallback(new SimpleResponse<VideoBean>()
			        {

				        @Override
				        public void onCacheResponse(
				                VolleyRequest<VideoBean> request,
				                VideoBean result, DataHull hull,
				                CacheResponseState state)
				        {
					        LogInfo.log("zhuqiao_time",
					                "****************获取本地视频所消耗时间"
					                        + (System.currentTimeMillis()
					                                - sRequestLocalConsumetime)
					                        + "毫秒****************");
					        sRequestLocalConsumetime = System
					                .currentTimeMillis()
					                - sRequestLocalConsumetime;

					        mIsLocalSuccess = state == CacheResponseState.SUCCESS;

					        // if (isVideoDownloaded()) {
					        // addPlayInfo("检查视频已缓存", "");
					        // mPlayInfo.albumPayConsumeTime =
					        // sRequestLocalConsumetime;
					        // startPlayLocal();
					        // }

					        mObservable.notifyObservers(
					                new FullControllerInitVideos(
					                        mIsNextPlayer));

					        // if (!mIsDownloadFile) {
					        // 如果是缓存视频，那么不需要再请求网络了
					        // requestNetwork();
					        EventBus.getDefault().post(new FetchMetaEvent());

					        // }
				        }

			        }).add();
		}

		/**
		 * 请求缓存数据
		 */
		// private void requestCache() {
		// requestLocalVideo(new Callback() {

		// @Override
		// public void callback() {
		// if (mCurrentPlayingVideo == null)
		// return;
		//
		// if (!BaseTypeUtils.isMapEmpty(mVideos)) {
		// mAid = mCurrentPlayingVideo.getPid();
		// mVid = mCurrentPlayingVideo.getId();
		// mCid = mCurrentPlayingVideo.getCid();
		// }
		//
		// if (mPlayRecord != null) {
		// mPlayRecord.setAlbumId((int) mAid);
		// }
		//
		// if (mIsDownloadFile) {
		// handlerFloatBall();
		// }
		//
		// if (mPlayRecord == null) {
		// mLoadListener.loadingVideo(mCurrentPlayingVideo.getNameCn());
		// }
		//
		// createPlayRecord(true);
		// if (mPlayRecord != null) {
		// mPlayRecord.setTotalDuration(mCurrentPlayingVideo.getDuration());
		// mPlayInfo.totalTime = mPlayRecord.getTotalDuration() * 1000;
		// }
		//
		// if (!mCurrentPlayingVideo.canPlay()) {
		// authentication();
		// }
		// }
		// });
		// }

		//
		// /**
		// * 若已下载的视频，未观看，则设置为已经观看，并刷新数据库
		// */
		// private void setWatched() {
		// new Thread() {
		//
		// @Override
		// public void run() {
		// DownloadDBBean info =
		// DBManager.getInstance().getDownloadTrace().getTitleInFinish(mVid);
		// if (info != null && info.getIsWatch() == 0) {
		// info.setIsWatch(1);
		// String filePath2 = info.getFilePath();
		// int lastIndexOf = filePath2.lastIndexOf("/");
		// String substring = filePath2.substring(0, lastIndexOf);
		// LogInfo.log("zhuqiao",
		// "video filepath=" + substring + "downloadinfo = " + filePath2);
		// info.setFilePath(substring);
		// DBManager.getInstance().getDownloadTrace().changeUserStatus(info);
		// }
		// }
		//
		// }.start();
		// }

		//
		// protected void onError(NetworkResponseState state) {
		// // if (state == NetworkResponseState.NETWORK_ERROR) {
		// // if (mIsDownloadFile) {
		// // return;
		// // }
		// // }
		//
		// mObservable.notifyObservers(AlbumPlayFlowObservable.ON_REQUEST_VIDEO_INFO_FAIL);
		// // 刷新全屏的视频列表
		// mObservable.notifyObservers(AlbumPlayFlowObservable.ON_SHOW_FULL_VIDEO_LIST_PLAY_NEXT);
		//
		// if (state == NetworkResponseState.NETWORK_ERROR ||
		// state == NetworkResponseState.NETWORK_NOT_AVAILABLE) {
		// // requestLocalVideo(null);
		// // Toast.makeText(mContext, "state:" + state + " net error!",
		// Toast.LENGTH_SHORT).show();
		// }
		//
		// // if (mIsDownloadFile) {
		// // return;
		// // }
		//
		// // mTrailListener.hide();
		//
		// if (state == NetworkResponseState.RESULT_ERROR) {
		// mLoadListener.requestError(mContext.getString(R.string.commit_error_info),
		// PlayErrCode.ADDRESS_OR_DATA_ACQUIRED_FAILED);
		// mObservable.notifyObservers(new
		// PlayErrorCodeNotify(PlayErrCode.ADDRESS_OR_DATA_ACQUIRED_FAILED,
		// true));
		// staticticsErrorInfo(mContext,
		// DataConstant.ERRORCODE.REQUEST_PLAY_NET_ER_ERROR, "playerError", 0,
		// -1);
		// } else if (state == NetworkResponseState.NETWORK_ERROR) {
		// mLoadListener.requestError(mContext.getString(R.string.commit_error_info),
		// PlayErrCode.ADDRESS_OR_DATA_ACQUIRED_FAILED);
		// mObservable.notifyObservers(new
		// PlayErrorCodeNotify(PlayErrCode.ADDRESS_OR_DATA_ACQUIRED_FAILED,
		// true));
		// } else if (state == NetworkResponseState.NETWORK_NOT_AVAILABLE) {
		// mLoadListener.requestError("", "");
		// mObservable.notifyObservers(new PlayErrorCodeNotify("", true));
		// }
		// mPlayCallBackState = 2;
		// }
	}

	public void reportLanuchAndInit()
	{
		/** 大数据视频初始化统计 **/
		VideoPlay startVideoPlay = getCommonVideoPlay();
		startVideoPlay.startInit();
		LeDimAnalysisUtils.reportInitPlayEvent(startVideoPlay);
		VideoPlay launchVideoPlay = getCommonVideoPlay();
		launchVideoPlay.launch();
		LeDimAnalysisUtils.reportInitPlayEvent(launchVideoPlay);

	}

	private VideoPlay mVideoPlay;

	/**
	 * @return 获取点播必备事件
	 */
	public VideoPlay getCommonVideoPlay()
	{
		if (mVideoPlay == null)
		{
			mVideoPlay = LeDimAnalysisUtils.generatePlayEvent();
		}
		LeDimAnalysisUtils.setVidoPlayCommonPro(mCid, mAid, mZid,
		        mAlbumUrl.realUrl, streamType, mPlayInfo.totalTime / 1000,
		        mPlayInfo.mIpt, mVideoPlay);
		if (mVid != 0)
		{
			mVideoPlay.setVideoId(String.valueOf(mVid));
		}
		return mVideoPlay;
	}

	/**
	 * 计时复位
	 */
	public void resetTime()
	{
		mPlayInfo = new AlbumPlayInfo();
	}

}
